package com.biqee.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

public class CsvUtils {
	
	private static final String DEFAULT_CSV_SPLIT_CHAR = ",";
	
	private static final String DEFAULT_CSV_VALUE_Quote = "\"";
	
	/**
	 * 将csv文件转换成对象列表
	 * @param csv
	 * @return
	 * @throws IOException
	 */
	public static List<Map<String,String>> parseCsv(InputStream csv ,String[] head) throws IOException{
		List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
		Reader reader  = null ;
		try{
		 reader = new InputStreamReader(csv,"GBK");
	    BufferedReader reader2 = new BufferedReader(reader);
	    String line = reader2.readLine();//第一行信息，为标题信息，如果指定了head就不用读取
	    if(head == null){
		  head = getLineFileds(line);
		   }       
        while(line!=null){
        	 line = reader2.readLine();
        	 String[] dataLine = getLineFileds(line);
        	 if(dataLine!=null&&head.length==dataLine.length){
        		 Map<String,String> dataMap = new HashMap<String,String>();
        		 for(int i=0; i<head.length;i++){
        			 dataMap.put(head[i],dataLine[i] );
        		 }
        		 mapList.add(dataMap);
        	 }
        	 
        }
		}catch(IOException exception){
			throw exception;
		}finally{
			if(reader!=null){
				reader.close();
			}
		}
        return mapList;

	}
	
	
	private static String[] getLineFileds(String line ){
		if(StringUtils.isBlank(line)){
			return null ;
		}
		String[] strs = line.split(DEFAULT_CSV_VALUE_Quote+DEFAULT_CSV_SPLIT_CHAR+DEFAULT_CSV_VALUE_Quote);
		strs[0]= strs[0].substring(1);
		strs[strs.length-1]= strs[strs.length-1].substring(0,strs[strs.length-1].length()-1);
		return strs ;
	}
}
